<?php
/**
 * @look Zend_Acl
 * Contain roles and right for ACL processing
 */

class Zen_Acl{

	protected static $instance;  // object instance

	/**
	 * Защищаем от создания через new Singleton
	 *
	 * @return Singleton
	 */
	private function __construct() {
	}

	/**
	 * Защищаем от создания через клонирование
	 *
	 * @return Singleton
	 */
	private function __clone() {
	}

	/**
	 * Защищаем от создания через unserialize
	 *
	 * @return Singleton
	 */
	private function __wakeup() {
	}

	/**
	 * Возвращает единственный экземпляр класса
	 *
	 * @return Singleton
	 */
	public static function getInstance() {
		if ( is_null(self::$instance) ) {
			$acl=self::loadAcl ();
			self::$instance = $acl;
		}
		return self::$instance;
	}



	static function loadAcl() {

		$cache = Zen_Cache_Factory::get('acl');
		$id = 'acllist';
		if ($acl = $cache->load ( $id )) {
			return($acl);
		} else {
			$acl=new Zend_Acl();
			$roles = self::loadRoles ();
			$resources = self::loadRes ();

			foreach ( $resources as $r ) {
				foreach ( $r ['res'] as $res ) {
					$acl->addResource ( $res );
				}
			}

			if ($roles != false) {
				foreach ( $roles as $role ) {
					$acl->addRole ( $role ['alias'] );
					if ($role ['resources'] != '') {
						$res = unserialize ( $role ['resources'] );
						if (sizeof ( $res ) > 0 && $res!=false) {
							foreach ( $res as $r ) {
								if (isset ( $resources [$r] )) {
									foreach ( $resources [$r] ['res'] as $addRes ) {
										$acl->allow ( $role ['alias'], $addRes );
									}
								}

							}
						}

					}
				}
			}
			$acl->addRole ( 'guest' );

			$cache->save ( $acl, $id );
			return $acl;
		}

	}

	static function loadRoles() {
		$rolesModel = new Zen_List ( 'user_role' );
		$roles = $rolesModel->select ()->setColumns ( array ('id', 'alias', 'resources' ) )->getData ();
		return $roles;
	}

	static function loadRes() {
		$cfg = Zend_Registry::get ( 'cnf' );
		$dir = $cfg->resources->frontController->moduleDirectory;
		$dir = $dir->toArray ();

		$data = array ();

		$modules = array ();
		foreach ( $dir as $d ) {
			$modules [$d] = scandir ( $d );
		}

		foreach ( $modules as $dir => $mods ) {
			foreach ( $mods as $module ) {
				$file = $dir . '/' . $module . '/settings/res.php';
				if (file_exists ( $file )) {
					include $file;
					foreach ( $resources as $res ) {
						$data [$res ['id']] = $res;
					}
				}
			}
		}

		if (sizeof ( $data ) > 0) {
			return $data;
		} else {
			return false;
		}
	}

}